import React, { Component } from 'react';
import { connect } from 'dva';
import FooterToolbar from '@/components/FooterToolbar';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import CascaderOptions from '@/utils/cascaderAddressOptions';

import {
  Form,
  Card,
  Popover,
  Icon,
  Select,
  DatePicker,
  Button,
  Row,
  Col,
  Input,
  Radio,
  InputNumber,
  AutoComplete,
  Cascader,
} from 'antd';
import RadioGroup from 'antd/lib/radio/group';
import TextArea from 'antd/lib/input/TextArea';
import styles from './TeacherCreate.less';

const { Option } = Select;
const { RangePicker } = DatePicker;
let guardianId = 0;

// 所属专业
const departments = {
  ch: '测绘中心实验室',
  yg: '遥感科学与技术系',
  zh: '资源环境与城乡规划管理系',
  cx: '土地资源管理系',
  dx: '测量工程系',
  tg: '地理信息科学系',
};
// 职称
const academicTitles = {
  assistant: '助教',
  lecture: '讲师',
  adjunctProfessor: '副教授',
  professor: '教授',
};
// 学位
const academicDegrees = { doctor: '博士', postDoctor: '博士后' };
// 职位
const divisions = [
  '党政办公室',
  '团委副书记',
  '学生工作办公室',
  '教学与科研工作办公室',
  '研究生工作办公室',
  '学院学位委员会',
  '学院学术委员会',
];

// 政治面貌
const politicalOutlooks = {
  partyMember: '中共党员',
  probationaryPartyMember: '中共预备党员',
  LeagueMember: '共青团员',
  masses: '群众',
};

const roles = {
  admin: '管理员',
  teacher: '教师',
  student: '学生',
};

const fieldLabels = {
  // 基本信息
  key: '身份证号',
  name: '姓名',
  age: '年龄',
  sex: '性别',
  department: '教学单位',
  politicalOutlook: '政治面貌',
  birthDate: '出生年月',
  nativePlace: '籍贯',

  // 联系信息
  contactNumber: '手机号',
  email: '邮箱',
  wechat: '微信号',
  qq: 'QQ号',
  postalAddress: '通讯地址',

  // 教育经历
  educationRange: '起始与结束时间',
  educationPlace: '学校名称',

  // 账号管理
  nichname: '用户昵称',
  password: '账户密码',
  role: '账户类型',

  // TODO:
  division: '职位',
  academicDegree: '学位',
  academicTitle: '职称',
  researchPlatforms: '科研平台',
  description: '个人介绍',
};

@connect(({ loading }) => ({
  submitting: loading.effects['students/add'],
}))
@Form.create()
class TeacherCreate extends Component {
  state = {
    width: '100%',
    emailDataSource: [],
  };

  componentDidMount() {
    window.addEventListener('resize', this.resizeFooterToolbar);
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.resizeFooterToolbar);
  }

  resizeFooterToolbar = () => {
    requestAnimationFrame(() => {
      const sider = document.querySelectorAll('.ant-layout-sider')[0];
      if (sider) {
        const width = `calc(100% - ${sider.style.width})`;
        const { width: stateWidth } = this.state;
        if (stateWidth !== width) {
          this.setState({ width });
        }
      }
    });
  };

  getErrorInfo = () => {
    const {
      form: { getFieldsError },
    } = this.props;
    const errors = getFieldsError();
    const errorCount = Object.keys(errors).filter(key => errors[key]).length;
    if (!errors || errorCount === 0) {
      return null;
    }
    const scrollToField = fieldKey => {
      const labelNode = document.querySelector(`label[for="${fieldKey}"]`);
      if (labelNode) {
        labelNode.scrollIntoView(true);
      }
    };
    const errorList = Object.keys(errors).map(key => {
      if (!errors[key]) {
        return null;
      }
      return (
        <li key={key} className={styles.errorListItem} onClick={() => scrollToField(key)}>
          <Icon type="cross-circle-o" className={styles.errorIcon} />
          <div className={styles.errorMessage}>{errors[key][0]}</div>
          <div className={styles.errorField}>{fieldLabels[key]}</div>
        </li>
      );
    });
    return (
      <span className={styles.errorIcon}>
        <Popover
          title="表单校验信息"
          content={errorList}
          overlayClassName={styles.errorPopover}
          trigger="click"
          getPopupContainer={trigger => trigger.parentNode}
        >
          <Icon type="exclamation-circle" />
        </Popover>
        {errorCount}
      </span>
    );
  };

  validate = () => {
    const {
      form: { validateFieldsAndScroll },
      dispatch,
    } = this.props;
    validateFieldsAndScroll((error, values) => {
      if (!error) {
        dispatch({
          type: 'students/add',
          payload: values,
        });
      }
    });
  };

  handleChange = value => {
    this.setState({
      emailDataSource:
        !value || value.indexOf('@') >= 0
          ? []
          : [
              `${value}@home.hpu.edu.cn`,
              `${value}@gmail.com`,
              `${value}@163.com`,
              `${value}@qq.com`,
            ],
    });
  };

  guardianFormRemove = k => {
    const { form } = this.props;
    const guardians = form.getFieldValue('guardians');
    if (guardians.length === 1) {
      return;
    }

    form.setFieldsValue({
      guardians: guardians.filter(key => key !== k),
    });
  };

  guardianFormAdd = () => {
    const { form } = this.props;
    const guardians = form.getFieldValue('guardians');
    const nextGuardians = guardians.concat(guardianId);
    guardianId += 1;

    form.setFieldsValue({
      guardians: nextGuardians,
    });
  };

  render() {
    const {
      form: { getFieldDecorator, getFieldValue },
      submitting,
    } = this.props;
    const { width, emailDataSource } = this.state;

    const prefixSelector = getFieldDecorator('prefix', {
      initialValue: '86',
    })(
      <Select style={{ width: 70 }}>
        <Option value="86">+86</Option>
        <Option value="87">+87</Option>
      </Select>
    );

    getFieldDecorator('guardians', { initialValue: [] });
    const guardians = getFieldValue('guardians');
    const guardianFormItems = guardians.map((k, index) => (
      <Row gutter={6} key={k}>
        <Col lg={10} md={10} sm={24}>
          <Form.Item label={fieldLabels.educationRange}>
            {getFieldDecorator(`educationRange[${index + 1}]`, {
              rules: [{ required: true, message: '请输入起始与结束时间！' }],
            })(<RangePicker format="YYYY-MM-DD" placeholder={['开始时间', '结束时间']} />)}
          </Form.Item>
        </Col>
        <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 10 }} sm={20}>
          <Form.Item label={fieldLabels.educationPlace}>
            {getFieldDecorator(`educationPlace[${index + 1}]`, {
              rules: [{ required: true, message: '请输入学校名称！' }],
            })(<Input placeholder="请输入学校名称" />)}
          </Form.Item>
        </Col>

        {/* <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 20 }} sm={20}>
          TODO
        </Col> */}
        <Col lg={{ span: 2 }} md={{ span: 2 }} sm={2}>
          {guardians.length > 1 ? (
            <Icon
              className={styles['dynamic-delete-button']}
              type="minus-circle-o"
              onClick={() => this.guardianFormRemove(k)}
            />
          ) : null}
        </Col>
      </Row>
    ));

    return (
      <PageHeaderWrapper title="新建教师" wrapperClassName={styles.advancedForm}>
        <Card title="基本信息" className={styles.card}>
          <Form layout="vertical" hideRequiredMark>
            <Row gutter={24}>
              <Col lg={6} md={12} sm={24}>
                <Form.Item label={fieldLabels.name}>
                  {getFieldDecorator('name', {
                    rules: [{ required: true, message: '请输入姓名！' }],
                  })(<Input placeholder="请输入姓名" />)}
                </Form.Item>
              </Col>

              <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
                <Form.Item label={fieldLabels.key}>
                  {getFieldDecorator('key', {
                    rules: [{ required: true, message: '请输入身份证号！' }],
                  })(<Input placeholder="请输入身份证号" />)}
                </Form.Item>
              </Col>

              <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
                <Form.Item label={fieldLabels.politicalOutlook}>
                  {getFieldDecorator('politicalOutlook', {
                    rules: [
                      {
                        required: true,
                        message: '请先选择政治面貌！',
                      },
                    ],
                  })(
                    <Select placeholder="请选择政治面貌">
                      {Object.keys(politicalOutlooks).map(key => (
                        <Option value={key} key={key}>
                          {politicalOutlooks[key]}
                        </Option>
                      ))}
                    </Select>
                  )}
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={16}>
              <Col lg={6} md={12} sm={24}>
                <Form.Item label={fieldLabels.birthDate}>
                  {getFieldDecorator('birthDate', {
                    rules: [{ required: true, message: '请选择出生日期！' }],
                  })(<DatePicker placeholder="请选择出生日期" />)}
                </Form.Item>
              </Col>
              <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
                <Form.Item label={fieldLabels.age}>
                  {getFieldDecorator('age', {
                    rules: [
                      {
                        required: true,
                        message: '请先输入年龄！',
                      },
                    ],
                    initialValue: 18,
                  })(
                    <InputNumber
                      placeholder="请先输入年龄"
                      style={{ width: '50%' }}
                      min={12}
                      max={30}
                    />
                  )}
                </Form.Item>
              </Col>
              <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
                <Form.Item label={fieldLabels.sex}>
                  {getFieldDecorator('sex', {
                    rules: [{ required: true, message: '请选择性别！' }],
                  })(
                    <RadioGroup>
                      <Radio value>男</Radio>
                      <Radio value={false}>女</Radio>
                    </RadioGroup>
                  )}
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={16}>
              <Col lg={6} md={12} sm={24}>
                <Form.Item label={fieldLabels.department}>
                  {getFieldDecorator('department', {
                    rules: [{ required: true, message: '请选择教学单位！' }],
                  })(
                    <Select placeholder="请选择教学单位">
                      {Object.keys(departments).map(key => (
                        <Option value={key} key={key}>
                          {departments[key]}
                        </Option>
                      ))}
                    </Select>
                  )}
                </Form.Item>
              </Col>
              <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
                <Form.Item label={fieldLabels.division}>
                  {getFieldDecorator('division', {
                    rules: [{ required: true, message: '请选择所属职位！' }],
                  })(
                    <Select placeholder="请选择职位">
                      {Object.keys(divisions).map(key => (
                        <Option value={key} key={key}>
                          {divisions[key]}
                        </Option>
                      ))}
                    </Select>
                  )}
                </Form.Item>
              </Col>
              <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
                <Form.Item label={fieldLabels.academicTitle}>
                  {getFieldDecorator('academicTitle', {
                    rules: [{ required: true, message: '请选择职称！' }],
                  })(
                    <Select placeholder="请选择职称">
                      {Object.keys(academicTitles).map(key => (
                        <Option value={key} key={key}>
                          {academicTitles[key]}
                        </Option>
                      ))}
                    </Select>
                  )}
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={16}>
              <Col lg={6} md={12} sm={24}>
                <Form.Item label={fieldLabels.academicDegree}>
                  {getFieldDecorator('academicDegree', {
                    rules: [{ required: true, message: '请选择学位！' }],
                  })(
                    <Select placeholder="请选择学历">
                      {Object.keys(academicDegrees).map(key => (
                        <Option value={key} key={key}>
                          {academicDegrees[key]}
                        </Option>
                      ))}
                    </Select>
                  )}
                </Form.Item>
              </Col>
              <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
                <Form.Item label={fieldLabels.nativePlace}>
                  {getFieldDecorator('nativePlace', {
                    rules: [
                      {
                        required: true,
                        message: '请输入籍贯！',
                      },
                    ],
                  })(<Cascader showSearch options={CascaderOptions} placeholder="请输入籍贯" />)}
                </Form.Item>
              </Col>
            </Row>

            <Row>
              <Col xl={12} lg={12} md={24} sm={24}>
                <Form.Item label={fieldLabels.description}>
                  {getFieldDecorator('description', {
                    rules: [
                      {
                        required: false,
                        message: '请输入个人描述！',
                      },
                    ],
                  })(
                    <TextArea autosize={{ minRows: 2, maxRows: 6 }} placeholder="请输入个人描述" />
                  )}
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card title="联系信息" className={styles.card} bordered={false}>
          <Form layout="vertical" hideRequiredMark>
            <Row gutter={16}>
              <Col lg={6} md={12} sm={24}>
                <Form.Item label={fieldLabels.contactNumber}>
                  {getFieldDecorator('contactNumber', {
                    rules: [
                      {
                        required: true,
                        message: '请输入手机号！',
                      },
                    ],
                  })(<Input addonBefore={prefixSelector} placeholder="请输入手机号" />)}
                </Form.Item>
              </Col>
              <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
                <Form.Item label={fieldLabels.email}>
                  {getFieldDecorator('email', {
                    rules: [
                      {
                        required: true,
                        message: '请输入邮箱地址！',
                      },
                    ],
                  })(
                    <AutoComplete
                      dataSource={emailDataSource}
                      placeholder="请输入邮箱地址"
                      onChange={this.handleChange}
                    />
                  )}
                </Form.Item>
              </Col>
              <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
                <Form.Item label={fieldLabels.postalAddress}>
                  {getFieldDecorator('postalAddress', {
                    rules: [
                      {
                        type: 'array',
                        required: true,
                        message: '请输入通讯地址！',
                      },
                    ],
                    initialValue: ['41', '4108', '410811'],
                  })(
                    <Cascader showSearch options={CascaderOptions} placeholder="请输入通讯地址" />
                  )}
                </Form.Item>
              </Col>
            </Row>

            {/* TODO submit 转化为 字符串 */}
            <Row gutter={16}>
              <Col lg={6} md={12} sm={24}>
                <Form.Item label={fieldLabels.wechat}>
                  {getFieldDecorator('wechat', {
                    rules: [
                      {
                        required: true,
                        message: '请输入微信号！',
                      },
                    ],
                  })(<Input placeholder="请输入微信号" />)}
                </Form.Item>
              </Col>
              <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
                <Form.Item label={fieldLabels.qq}>
                  {getFieldDecorator('qq', {
                    rules: [
                      {
                        required: true,
                        message: '请输入QQ号！',
                      },
                    ],
                  })(<Input placeholder="请输入QQ号" />)}
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card title="教育经历" className={styles.card} bordered={false}>
          <Form layout="vertical" hideRequiredMark>
            {guardianFormItems}

            <Row justify="center">
              <Col span={16}>
                <Form.Item>
                  <Button type="dashed" onClick={this.guardianFormAdd} style={{ width: '60%' }}>
                    <Icon type="plus" /> 添加教育经历
                  </Button>
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card title="账户管理" className={styles.card} bordered={false}>
          <Form layout="vertical" hideRequiredMark>
            <Row gutter={16}>
              <Col lg={6} md={12} sm={24}>
                <Form.Item label={fieldLabels.nichname}>
                  {getFieldDecorator('nichname', {
                    rules: [{ required: true, message: '请输入昵称！' }],
                  })(
                    <Input
                      prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
                      placeholder="请输入昵称"
                    />
                  )}
                </Form.Item>
              </Col>
              <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
                <Form.Item label={fieldLabels.password}>
                  {getFieldDecorator('password', {
                    rules: [{ required: true, message: '请输入密码！' }],
                  })(
                    <Input.Password
                      placeholder="请输入密码"
                      prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
                    />
                  )}
                </Form.Item>
              </Col>

              <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
                <Form.Item label={fieldLabels.role}>
                  {getFieldDecorator('role', {
                    rules: [{ required: true, message: '请选择账号类型！' }],
                    initialValue: 'teacher',
                  })(
                    <Select placeholder="请选择账号类型" disabled>
                      {Object.keys(roles).map(key => (
                        <Option value={key} key={key}>
                          {roles[key]}
                        </Option>
                      ))}
                    </Select>
                  )}
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Card>

        <FooterToolbar style={{ width }}>
          {this.getErrorInfo()}
          <Button type="primary" onClick={this.validate} loading={submitting}>
            提交
          </Button>
        </FooterToolbar>
      </PageHeaderWrapper>
    );
  }
}

export default TeacherCreate;
